package com.wish233.wiliwiligateway.filter;

import com.wish233.wiliwilicommon.common.BaseResponse;
import com.wish233.wiliwilicommon.common.ErrorCode;
import com.wish233.wiliwilicommon.common.ResultUtils;
import com.wish233.wiliwilicommon.exception.BusinessException;
import org.springframework.boot.web.reactive.error.ErrorWebExceptionHandler;
import org.springframework.core.annotation.Order;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.http.server.reactive.ServerHttpRequest;
import org.springframework.http.server.reactive.ServerHttpResponse;
import org.springframework.stereotype.Component;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;

/**
 * Spring Cloud Gateway 全局异常处理
 * @author WHH
 */
@Component
@Order(-1) // 确保优先级高于默认的 DefaultErrorWebExceptionHandler
public class GlobalGatewayExceptionHandler implements ErrorWebExceptionHandler {

    @Override
    public Mono<Void> handle(ServerWebExchange exchange, Throwable ex) {
        ServerHttpRequest request = exchange.getRequest();
        ServerHttpResponse response = exchange.getResponse();

        // 设置响应状态码
        // 统一返回 200，具体错误码在 BaseResponse 中体现
        response.setStatusCode(HttpStatus.OK);
        response.getHeaders().setContentType(MediaType.APPLICATION_JSON);

        // 根据异常类型返回不同的错误信息
        BaseResponse<?> errorResponse;
        if (ex instanceof BusinessException) {
            BusinessException businessException = (BusinessException) ex;
            errorResponse = ResultUtils.error(businessException.getCode(), businessException.getMessage());
        } else if (ex instanceof RuntimeException) {
            errorResponse = ResultUtils.error(ErrorCode.SYSTEM_ERROR, "系统错误");
        } else {
            errorResponse = ResultUtils.error(ErrorCode.SYSTEM_ERROR, "未知错误");
        }

        // 将错误信息写入响应体
        return response.writeWith(Mono.just(response.bufferFactory()
                .wrap(errorResponse.toString().getBytes())));
    }
}